package net.guoyixian.admin.shiro;

import java.util.HashMap;
import java.util.Map;

import net.guoyixian.common.web.GyxResult;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class DefaultExceptionHandler {

	/**
	 * 无权限Exception
	 * @param request
	 * @param e
	 * @return
	 */
	@ExceptionHandler({ UnauthorizedException.class })
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public ModelAndView processUnauthorizedException(
			NativeWebRequest request, UnauthorizedException e) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("exception", e);
		mv.setViewName("unauthorized");
		return mv;
	}
	
	@ExceptionHandler({ UnauthenticatedException.class })
	public String processUnauthenticatedException(UnauthenticatedException e) {
		return "redirect:/login.do";
	}
		
	/**
	 * 用户不存在
	 * @param e
	 * @return
	 */
	@ExceptionHandler({ UnknownAccountException.class })
	@ResponseBody
	public GyxResult processUnknownAccountException(UnknownAccountException e) {
		return GyxResult.build(201, "该用户不存在!");
	}
	
	/**
	 * 该账号已被锁定，请联系管理员!
	 * @param e
	 * @return
	 */
	@ExceptionHandler({ LockedAccountException.class })
	@ResponseBody
	public GyxResult processLockedAccountException(LockedAccountException e) {
		return GyxResult.build(201, "该账号已被锁定，请联系管理员!");
	}
	
	/**
	 * 密码错误!
	 * @param e
	 * @return
	 */
	@ExceptionHandler({ AuthenticationException.class })
	@ResponseBody
	public GyxResult processAuthenticationException(AuthenticationException e) {
		return GyxResult.build(201, "密码错误!");
	}
	
	/**
	 * 文件上传超过了大小限制
	 */
	@ExceptionHandler({ MaxUploadSizeExceededException.class })
	@ResponseBody
	public Map processMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
		Map map = new HashMap();
		map.put("status", "error");
		map.put("message", "上传文件过大，超过了限制"+e.getMaxUploadSize()+"！");
		return map;
	}
	
	
}